<template>
  <el-row class="user-info-form" type="flex" justify="center" v-loading="loading">
    <el-col>
      <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
        <input type="hidden" v-model="editForm.id" />
        <!-- <el-form-item label="业主单位：" prop="orgId">
                  <el-select filterable v-model="editForm.orgId">
                    <el-option
                      v-for="item in orgOptions"
                      :key="item.organizationId"
                      :label="item.shortName"
                      :value="item.organizationId">
                    </el-option>
                  </el-select>
        </el-form-item>-->
        <el-form-item label="安全制度名称：" prop="name">
          <el-input v-model.trim="editForm.name" auto-complete="off" placeholder="请输入安全制度名称"></el-input>
        </el-form-item>
        <el-form-item label="消防安全管理制度明细：">
          <quill-editor
            ref="myQuillEditor"
            v-model="editForm.systemContent"
            :options="util.intEditorOptions()"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          ></quill-editor>
          <!-- 文件上传input 将它隐藏-->
          <el-upload
            :action="QINIUUPLOADURL"
            :before-upload="beforeAvatarUploadEditor"
            :data="qiniuDataEditor"
            :on-success="handleAvatarSuccessEditor"
            ref="uploadEditor"
            style="display:none"
          >
            <el-button size="small" type="primary" id="imgInput">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeDialog()">取消</el-button>
          <el-button type="primary" round @click="saveEdit('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import util from '@/utils/util'
import { getOrgList } from '@/api/org'
import { qnToken } from '@/api/api'
import { updateSafetManagementSystem } from '@/api/safeRule'

export default {
  name: 'SafeRuleForm',
  props: {
    editInfo: {
      type: Object,
      required: false,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
  },
  // 页面加载后执行 为编辑器的图片图标和视频图标绑定点击事件
  mounted() {
    // 为图片ICON绑定事件  getModule 为编辑器的内部属性
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('image', this.imgHandler)
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('video', this.videoHandler) // 为视频ICON绑定事件
  },
  data() {
    return {
      qiniuDataEditor: {
        //富文本编辑器相关  消防安全管理制度明细
        token: '',
        key: '',
        fileList: [],
      },
      defaultImg: this.GLOBAL.defaultImg,
      util: util,
      loading: false,
      //orgOptions: [],
      editForm: {
        id: 0,
        orgId: '' /*this.$store.state.userinfo.org.id*/,
        name: '',
        systemContent: '',
        createAccount: this.$store.state.userinfo.accountName,
        updateAccount: this.$store.state.userinfo.accountName,
      },
      editFormRules: {
        name: [
          { required: true, message: '请输入安全制度名称', trigger: 'blur' },
        ],
        orgId: [
          { required: true, message: '请选择业主单位', trigger: 'change' },
        ],
      },
    }
  },
  created() {
    //绑定下拉框
    /*getOrgList({queryType: 0}).then((data)=>{
         this.orgOptions.push.apply(this.orgOptions,data.data);
      })*/
    let infoObj = this.editInfo
    this.editForm.orgId = infoObj.orgId
    if (infoObj.id) {
      //编辑
      this.editForm.id = infoObj.id
      this.editForm.name = infoObj.name
      this.editForm.systemContent = infoObj.systemContent
      this.editForm.createAccount = infoObj.createAccount
    }
    this.getToken() //获取token
  },
  methods: {
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuDataEditor.token = result.data //富文本编辑器相关
      })
    },
    //--------------------BEGIN  富文本编辑器相关------------------------------//
    beforeAvatarUploadEditor: function (file) {
      //重命名和校验
      this.loading = true
      const suffix = file.name.split('.')
      const ext = suffix.splice(suffix.length - 1, 1)[0]
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuDataEditor.key = 'ilink_' + new Date().getTime() + fielType
    },
    handleAvatarSuccessEditor: function (res, file, fileList) {
      //上传成功
      this.loading = false
      let vm = this
      let url = QINIUUPLOADURL.indexOf('uploadFile')>-1? res.data:QINIUPATH+res.key
      if (url != null && url.length > 0) {
        // 将文件上传后的URL地址插入到编辑器文本中
        let value = url
        vm.qiniuDataEditor.fileList = vm.$refs.myQuillEditor.quill.getSelection()
        vm.$refs.myQuillEditor.quill.insertEmbed(
          vm.qiniuDataEditor.fileList !== null
            ? vm.qiniuDataEditor.fileList.index
            : 0,
          vm.uploadType,
          value
        ) // 调用编辑器的 insertEmbed 方法，插入URL
      } else {
        this.$message.error('上传失败')
      }
      this.$refs['uploadEditor'].clearFiles() // 插入成功后清除input的内容
    },
    // 点击图片ICON触发事件
    imgHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'image'
    },
    // 点击视频ICON触发事件
    videoHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'video'
    },
    // 编辑器光标离开 将编辑器内容发射给父组件
    onEditorBlur(editor) {
      this.$emit('getValue', this.editForm.systemContent)
    },
    // 编辑器获得光标
    onEditorFocus(editor) {
      editor.enable(true) // 实现达到上限字符可删除
    },
    // 编辑器文本发生变化
    onEditorChange({ editor, html, text }) {
      let textLength = text.length
      if (textLength > 10000) {
        this.$message.error('最多输入10000个字符')
        editor.enable(false)
      }
      this.$emit('getValue', this.editForm.systemContent)
    },
    // 清除编辑器内容
    callMethod() {
      this.editForm.systemContent = ''
    },
    //--------------------END  富文本编辑器相关------------------------------//
    saveEdit(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.editForm
          updateSafetManagementSystem(parames).then((res) => {
            that.$message({
              message: '保存成功！',
              type: 'success',
            })
            that.closeDialog(true)
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>
